<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件上传示例</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
      }

      .upload-container {
        border: 2px dashed #ccc;
        padding: 20px;
        text-align: center;
        margin-bottom: 20px;
      }

      .result {
        background-color: #f5f5f5;
        padding: 15px;
        border-radius: 5px;
        display: none;
      }

      .error {
        color: red;
        margin-top: 10px;
        display: none;
      }
    </style>
  </head>

  <body>
    <h1>文件上传示例</h1>
    <div class="upload-container">
      <form id="uploadForm">
        <input type="file" name="file" required />
        <button type="submit">上传文件</button>
      </form>
      <div class="error" id="error"></div>
    </div>
    <div class="result" id="result">
      <h3>上传结果：</h3>
      <p>文件ID：<span id="fileId"></span></p>
      <p>文件名：<span id="fileName"></span></p>
      <p>文件URL：<a id="fileUrl" target="_blank"></a></p>
    </div>

    <script>
      document.getElementById('uploadForm').addEventListener('submit', async (e) => {
        e.preventDefault()
        console.log(e.target)
        const formData = new FormData(e.target)

        const errorDiv = document.getElementById('error')
        const resultDiv = document.getElementById('result')
        console.log('formData', formData)

        try {
          errorDiv.style.display = 'none'
          const response = await fetch('http://localhost:2230/api/files/upload', {
            method: 'POST',
            body: formData,
          })

          if (!response.ok) {
            throw new Error('上传失败')
          }

          const data = await response.json()
          document.getElementById('fileId').textContent = data.id
          document.getElementById('fileName').textContent = data.name
          const fileUrl = document.getElementById('fileUrl')
          // url: /uploads/3bafcf28-0f26-474f-b26f-7354ab9cbd6e.docx
          fileUrl.href = 'http://localhost:2230' + data.url
          fileUrl.textContent = 'http://localhost:2230' + data.url 
          resultDiv.style.display = 'block'
        } catch (error) {
          errorDiv.textContent = error.message
          errorDiv.style.display = 'block'
          resultDiv.style.display = 'none'
        }
      })
    </script>
  </body>
</html>
